package com.cz.run.config.mvc;

import com.cz.run.constants.ConstantKey;
import com.cz.run.utils.HttpResponseUtil;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author CAIYJ
 * @Description: TODO()
 * @Date:2018/5/25 23:09
 */
public class AccessHandlerInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token == null) {
            HttpResponseUtil.noAuth(response);
            return false;
        }
        String userId = null;
        try {
            userId = Jwts.parser().setSigningKey(ConstantKey.SIGNING_KEY)
                    .parseClaimsJws(token)
                    .getBody().getSubject();
        } catch (Exception e) {
            HttpResponseUtil.noAuth(response);
            return false;
        }
        if (null == userId) {
            HttpResponseUtil.noAuth(response);
            return false;
        }
        request.setAttribute(ConstantKey.USER_KEY, userId);
        return true;
    }


    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        // TODO Auto-generated method stub

    }
}
